const connection = require('../sql'); // 假设这是你的数据库连接模块

class SimpleDataScopeHelper {
	constructor() {
		this.scope = new Map();
	}

	start(tableName) {
		this.scope.set(process.pid, { tableName, conditions: null });
	}

	setConditions(conditions) {
		const context = this.scope.get(process.pid);
		if (context) context.conditions = conditions;
	}

	getConditions() {
		const context = this.scope.get(process.pid);
		return context?.conditions || { whereClause: '', params: [] };
	}

	clearDataScope() {
		this.scope.delete(process.pid);
	}

	/**
	 * 生成数据权限的 WHERE 条件
	 * @param {string} userId - 用户 ID
	 * @param {string} tableName - 目标表名
	 * @returns {Promise<{ whereClause: string, params: any[] }>} - WHERE 子句和参数
	 */
	async applyScope(userId, tableName) {
		try {
			const isAdminSql = `SELECT
  			sr.permissions 
			FROM
 			 sys_user_role udr
  			LEFT JOIN sys_role sr ON udr.role_id = sr.id 
			WHERE
 			 udr.user_id = ? 
  			AND sr.del_flag = 'F'`;
			const [isAdmin] = await connection.query(isAdminSql, [userId]);
			if (isAdmin[0].permissions == 'admin') {
				return { whereClause: '', params: [] };
			}
			// 获取用户数据角色
			const roleSql = `
        SELECT dr.id, dr.data_scope_cd
        FROM sys_user_data_role udr
        JOIN sys_data_role dr ON udr.role_id = dr.id
        WHERE udr.user_id = ? AND dr.del_flag = 'F'
      `;
			const [roles] = await connection.execute(roleSql, [userId]);

			if (!roles.length) {
				return { whereClause: 'WHERE 1=0', params: [] }; // 无角色，禁止访问
			}

			// 获取用户部门
			const deptSql = `
        SELECT dept_id 
        FROM sys_user_dept 
        WHERE user_id = ?
      `;
			const [deptRows] = await connection.execute(deptSql, [userId]);
			const userDeptIds = deptRows.map((row) => row.dept_id);

			// 检查超级管理员
			/* const superAdminSql = `
        SELECT role_id 
        FROM sys_data_role
        WHERE id = ?
      `; */
			// 检查超级管理员
			const superAdminSql = `
        SELECT 1 
        FROM sys_user 
        WHERE id = ? AND user_tag_cd = '1001002' AND del_flag = 'F'
      `;
			const [superAdminRows] = await connection.execute(superAdminSql, [userId]);
			const isSuperAdmin = superAdminRows.length > 0;

			let whereClause = '';
			const params = [];

			for (const role of roles) {
				const { id: roleId, data_scope_cd } = role;

				if (data_scope_cd === '1006001' || isSuperAdmin) {
					// 全部权限或超级管理员，放行
					return { whereClause: '', params: [] };
				} else if (data_scope_cd === '1006002') {
					// 本部门及以下
					if (!userDeptIds.length) continue;
					const deptClosureSql = `
            SELECT descendant_id 
            FROM sys_dept_closure 
            WHERE ancestor_id IN (${userDeptIds.map(() => '?').join(',')})
          `;
					const [closureRows] = await connection.execute(deptClosureSql, userDeptIds);
					const allDeptIds = [...new Set([...userDeptIds, ...closureRows.map((r) => r.descendant_id)])];
					whereClause += whereClause ? ' OR ' : '';
					whereClause += `EXISTS (
            SELECT 1 
            FROM sys_user_dept 
            WHERE sys_user_dept.dept_id IN (${allDeptIds.map(() => '?').join(',')})
            AND ${tableName}.create_id = sys_user_dept.user_id
          )`;
					params.push(...allDeptIds);
				} else if (data_scope_cd === '1006003') {
					// 仅本部门
					if (!userDeptIds.length) continue;
					whereClause += whereClause ? ' OR ' : '';
					whereClause += `EXISTS (
            SELECT 1 
            FROM sys_user_dept 
            WHERE sys_user_dept.dept_id IN (${userDeptIds.map(() => '?').join(',')})
            AND ${tableName}.create_id = sys_user_dept.user_id
          )`;
					params.push(...userDeptIds);
				} else if (data_scope_cd === '1006004') {
					// 仅本人
					whereClause += whereClause ? ' OR ' : '';
					whereClause += `${tableName}.create_id = ?`;
					params.push(userId);
				} else if (data_scope_cd === '1006005') {
					// 自定义权限
					const relSql = `
            SELECT relation_type_cd, relation_id 
            FROM sys_data_role_relation 
            WHERE role_id = ?
          `;
					const [rels] = await connection.execute(relSql, [roleId]);
					const deptIds = rels.filter((r) => r.relation_type_cd === 'dept').map((r) => r.relation_id);
					const userIds = rels.filter((r) => r.relation_type_cd === 'user').map((r) => r.relation_id);

					if (deptIds.length || userIds.length) {
						whereClause += whereClause ? ' OR ' : '';
						whereClause += '(';
						if (deptIds.length) {
							whereClause += `EXISTS (
                SELECT 1 
                FROM sys_user_dept 
                WHERE sys_user_dept.dept_id IN (${deptIds.map(() => '?').join(',')})
                AND ${tableName}.create_id = sys_user_dept.user_id
              )`;
							params.push(...deptIds);
						}
						if (userIds.length) {
							whereClause += deptIds.length ? ' OR ' : '';
							whereClause += `${tableName}.create_id IN (${userIds.map(() => '?').join(',')})`;
							params.push(...userIds);
						}
						whereClause += ')';
					}
				} else {
					// 默认仅本人
					whereClause += whereClause ? ' OR ' : '';
					whereClause += `${tableName}.create_id = ?`;
					params.push(userId);
				}
			}

			return { whereClause: whereClause ? `WHERE ${whereClause}` : 'WHERE 1=0', params };
		} catch (error) {
			console.error(`Error applying data scope for user ${userId} on table ${tableName}:`, error);
			return { whereClause: 'WHERE 1=0', params: [] };
		}
	}
}

module.exports = new SimpleDataScopeHelper();
